package cn.minimelon.api.controller.system;


import cn.hutool.core.util.ObjUtil;
import cn.minimelon.api.constant.UserConstants;
import cn.minimelon.api.controller.common.BaseController;
import cn.minimelon.api.domain.common.AjaxResult;
import cn.minimelon.api.domain.common.LoginUser;
import cn.minimelon.api.domain.common.TableDataInfo;
import cn.minimelon.api.domain.system.SysRole;
import cn.minimelon.api.domain.system.SysUser;
import cn.minimelon.api.domain.system.SysUserRole;
import cn.minimelon.api.service.common.TokenService;
import cn.minimelon.api.service.system.ISysLoginService;
import cn.minimelon.api.service.system.ISysRoleService;
import cn.minimelon.api.service.system.ISysUserService;
import org.noear.solon.annotation.*;

import java.util.List;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@Controller
@Mapping("/system/role")
public class SysRoleController extends BaseController {
    @Inject
    ISysRoleService roleService;

    @Inject
    TokenService tokenService;

    @Inject
    ISysLoginService userLoginService;

    @Inject
    ISysUserService userService;

    @Get
    @Mapping("/list")
    public TableDataInfo list(SysRole role) {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @Get
    @Mapping(value = "/{roleId}")
    public AjaxResult getInfo(@Param Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @Post
    @Mapping
    public AjaxResult add(SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(getUsername());
        return toAjax(roleService.insertRole(role));
    }

    /**
     * 修改保存角色
     */
    @Put
    @Mapping
    public AjaxResult edit(SysRole role) {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(getUsername());

        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (ObjUtil.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(userLoginService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @Put
    @Mapping("/dataScope")
    public AjaxResult dataScope(SysRole role) {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @Put
    @Mapping("/changeStatus")
    public AjaxResult changeStatus(SysRole role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @Delete
    @Mapping("/{roleIds}")
    public AjaxResult remove(@Param Long[] roleIds) {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @Get
    @Mapping("/optionselect")
    public AjaxResult optionSelect() {
        return AjaxResult.success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @Get
    @Mapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectAllocatedList(user);
        return getDataTable(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @Get
    @Mapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList(user);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @Put
    @Mapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(SysUserRole userRole) {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @Put
    @Mapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds) {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @Put
    @Mapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds) {
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }
}
